using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Abp.Dapper.Repositories;
using Abp.Dependency;
using Abp.Domain.Entities.Auditing;
using Abp.Domain.Repositories;
using Abp.EntityFrameworkCore.Repositories;
using Abp.Threading.BackgroundWorkers;
using Abp.Threading.Timers;
using Castle.Core.Logging;
using Yozeev.BusinessLogic;
using Yozeev.BusinessLogic.DeviceManagement.DomainService;
using Yozeev.Database;
using EFCore.BulkExtensions;

namespace Yozeev.BackgroundWorkers
{
    public class OnlineScheduleManageWorker : PeriodicBackgroundWorkerBase, ISingletonDependency
    {
        private readonly IRepository<Schedule, Guid> _scheduleRepository;

        public OnlineScheduleManageWorker(AbpTimer timer, 
            IRepository<Schedule, Guid> scheduleRepository
            ) : base(timer)
        {
            _scheduleRepository = scheduleRepository;
            Timer.Period = 1000 * 60; // process every one minute
        }

        protected override async void DoWork()
        {
            this.Timer.Stop();
            //查询所有状态不是航行结束的航班
            var schedules = await _scheduleRepository.GetAllListAsync()/*.Where(m => m.ScheduleStatus != ScheduleStatusEnum.Ending).ToList()*/;
            var temp = schedules.ToList();
            foreach (var schedule in temp)
            {
                //大于验票时间
                if (DateTime.Now >= schedule.CheckStartTime && DateTime.Now <= schedule.CheckEndTime)
                {
                    schedule.ScheduleStatus = ScheduleStatusEnum.BeginCheck;
                }
                //大于开始时间
                if (DateTime.Now > schedule.CheckEndTime && DateTime.Now <= schedule.EndTime)
                {
                    schedule.ScheduleStatus = ScheduleStatusEnum.ScheduleRunning;
                }
                //大于结束时间
                if (DateTime.Now > schedule.EndTime)
                {
                    schedule.ScheduleStatus = ScheduleStatusEnum.Ending;
                }
               await _scheduleRepository.UpdateAsync(schedule);
            }
            this.Timer.Start();
        }
    }
}
